package com.wonsec.useragent.controller;

import com.wonsec.useragent.repository.ChannelTrackingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author： mzy
 * @Date： 2025/5/13 下午2:54
 * @Describe：
 */
@RestController
@RequestMapping("/analytics")
public class AnalyticsController {

    @Autowired
    private ChannelTrackingRepository channelTrackingRepository;

    @GetMapping("/channel-stats")
    public ResponseEntity<?> getChannelStats() {
        List<Object[]> stats = channelTrackingRepository.countByChannel();
        Map<String, Long> result = stats.stream()
                .collect(Collectors.toMap(
                        arr -> (String) arr[0],
                        arr -> (Long) arr[1]
                ));
        return ResponseEntity.ok(result);
    }

    @GetMapping("/channel-trend")
    public ResponseEntity<?> getChannelTrend(
            @RequestParam String startDate,
            @RequestParam String endDate) {

        LocalDateTime start = LocalDateTime.parse(startDate + "T00:00:00");
        LocalDateTime end = LocalDateTime.parse(endDate + "T23:59:59");

        List<Object[]> trendData = channelTrackingRepository.countByDateAndChannel(start, end);

        // 处理成前端需要的格式
        // ...

        return ResponseEntity.ok(trendData);
    }
}
